package com.aaa.rabbitmq.eight;

import com.aaa.rabbitmq.one.util.RabbitMQUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 正常消费者接受消息 消费者1
 * 为了死信队列 消息进入死信队列的三个要素
 * 1，消息被拒绝 2，消息TTL时间过期 3，队列达到最大长度
 */
public class ReceiveLogsNormal01 {

    //普通交换机的名称
    public static final String NORMAL_EXCHANGE_NAME = "normal_exchange";
    //死信交换机名称
    public static final String DEAD_EXCHANGE_NAME = "dead_exchange";
    //普通队列
    public static final String NORMAL_QUEUE_NAME = "normal_queue";
    //死信队列
    public static final String DEAD_QUEUE_NAME = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtil.getChannel();
        //声明死信和普通交换机  类型为direct 直接类型
        channel.exchangeDeclare(NORMAL_EXCHANGE_NAME,BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE_NAME,BuiltinExchangeType.DIRECT);

        /**
         * 将普通队列过期时间设置为10s，过期的消息转发到死信交换机中的死信队列
         */
        Map<String, Object> arguments = new HashMap<>();
        //arguments.put("x-message-ttl",100000);                      //设置过期时间 单位毫秒  也可以生产者发送消息时配置过期时间
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE_NAME);     //设置正常队列死信交换机
        arguments.put("x-dead-letter-routing-key","lisi");              //设置死信队列的routingkey
        //arguments.put("x-max-length",6);                            //设置队列最大长度  发送十个四个进入死信

        //声明普通队列和死信队列
        channel.queueDeclare(NORMAL_QUEUE_NAME,false,false,false,arguments);
        channel.queueDeclare(DEAD_QUEUE_NAME,false,false,false,null);

        //绑定交换机和队列
        channel.queueBind(NORMAL_QUEUE_NAME,NORMAL_EXCHANGE_NAME,"zhangsan");
        channel.queueBind(DEAD_QUEUE_NAME,DEAD_EXCHANGE_NAME,"lisi");
        System.out.println("等待消息。。");


        ////////////////////////////////////////////////////////

        //接受消息的回调
        DeliverCallback callback = (tag, message )->{
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            //如果是info5就拒绝，info5将会拒绝掉
            if (msg.equals("info5")){
                System.out.println("ReceiveLogsNormal01拒绝了："+msg);
                //1,哪个标签，2是否放回队列 flase拒绝队列，true将队列再放回去
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("ReceiveLogsNormal01：打印收到的消息"+new String(message.getBody(), StandardCharsets.UTF_8)+"=====RoutingKey: "+message.getEnvelope().getRoutingKey());
                //不批量应答
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };

        //手动应答
        channel.basicConsume(NORMAL_QUEUE_NAME,false,callback,consumerTage->{});


    }
}
